/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Views;

import Common.ChagesLanguage;
import Common.CheckForm;
import Common.ConnectionDB;
import Common.Constant;
import DAO.BillsDAO;
import DAO.ItemDAO;
import DAO.PaymentDAO;
import Helper.BillsHepler;
import Helper.ItemHelper;
import Helper.PaymentHelper;
import Model.BillsModel;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author KIENLT
 */
public class BillsDetail extends javax.swing.JDialog {

    ArrayList<BillsHepler> arrBills;
    ArrayList<BillsHepler> arrBillsList;
    BillsHepler billsData;
    Bills bills;
    ResultSet rs = null;
    private String BillsId;
    JPopupMenu popmenu1;
    Vector vtUpdate;
    ResourceBundle rb;
    private HashMap mapStore;
    private PaymentHelper paymenttemp;
    private String strTotal;

    /**
     * Creates new form BillsDetail
     */
    public BillsDetail(Bills bills, boolean modal, String billsId) {
        super(bills, modal);
        this.BillsId = billsId;
        this.bills = bills;
        initComponents();
        this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        loadLanguage();
        loadItemBills();
        loadComboboxPayment();
        loadBills();
        popmenu1 = new JPopupMenu();
        buildPopupMenu();
        this.setLocationRelativeTo(null);
        try {
            setIconImage(Toolkit.getDefaultToolkit().getImage(new File("src\\Images\\Icon-Form.png").getCanonicalPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadComboboxPayment() {
        cboPayment.removeAllItems();
        try {
            ResultSet rs = PaymentDAO.FindAll(ConnectionDB.ConnectionDatabase());
            mapStore = new HashMap();
            while (rs.next()) {
                String strId = rs.getString("PID");
                String strName = rs.getString("PName");
                paymenttemp = new PaymentHelper(strId, strName);
                mapStore.put(strId, paymenttemp);
                cboPayment.addItem(paymenttemp);
            }
        } catch (Exception ex) {
            try {
                ConnectionDB.CloseDB(rs);
            } catch (Exception ex1) {
                Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }

    private void buildPopupMenu() {

        JMenuItem menu1 = new JMenuItem("Update");
        menu1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    rs = ItemDAO.FindQuantity(ConnectionDB.ConnectionDatabase(), billsData.getItemId());
                    if (rs.next()) {
                        int result = Integer.parseInt(rs.getString("QuantityAvailable")) - Integer.parseInt(billsData.getQuantity());
                        if (result < 0) {
                            JOptionPane.showMessageDialog(BillsDetail.this, rb.getString("Quantitynotenough") +".", rb.getString("Warning"), JOptionPane.WARNING_MESSAGE);
                            return;
                        }
                    }
                    BillsDAO.UpdateBillDetail(ConnectionDB.ConnectionDatabase(), billsData);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(BillsDetail.this, rb.getString("Quantityisnotnumber") + ".", rb.getString("Warning"), JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        popmenu1.add(menu1);
    }

    private void loadLanguage() {
        ChagesLanguage.readFileLanguage();
        Locale locale = new Locale(ChagesLanguage.languageCode, ChagesLanguage.countryCode);
        rb = ResourceBundle.getBundle(ChagesLanguage.urlLanguage, locale);
        lblId.setText(rb.getString("Id"));
        lblCusName.setText(rb.getString("Cusname"));
        lblDiscount.setText(rb.getString("discount"));
        lblPayment.setText(rb.getString("payment"));
        lblUserName.setText(rb.getString("Username"));
        lblVat.setText(rb.getString("vat"));
        btnCreate.setText(rb.getString("Create"));
        btnCancel.setText(rb.getString("cancelbills"));
        btnUpdate.setText(rb.getString("added"));
        lblTotal.setText(rb.getString("Total"));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(rb.getString("Items")));
        this.setTitle(rb.getString("BillsDetail"));
    }

    private void loadBills() {
        try {
            billsData = new BillsHepler();
            billsData.setId(getBillsId());
            rs = BillsDAO.FindOne(ConnectionDB.ConnectionDatabase(), billsData);
            if (rs.next()) {
                txtId.setText(rs.getString("BID"));
                txtCusname.setText(rs.getString("CName"));
                txtUsername.setText(rs.getString("Username"));
            }
        } catch (Exception ex) {
            Logger.getLogger(BillsDetail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void loadItemBills() {
        try {
            billsData = new BillsHepler();
            billsData.setId(getBillsId());
            arrBills = BillsDAO.FindItemBills(ConnectionDB.ConnectionDatabase(), billsData);
            arrBillsList = new ArrayList<BillsHepler>();

            for (BillsHepler item : arrBills) {
                arrBillsList.add(item);
            }

            tblBills.setModel(new BillsModel(arrBillsList));
            int total = 0;
            for (int i = 0; i < arrBillsList.size(); i++) {
                total += Integer.parseInt(((BillsHepler) arrBillsList.get(i)).getTotal());
            }
            lblTotalNumber.setText(String.valueOf(total));
            strTotal = String.valueOf(total);
            DefaultTableColumnModel model = (DefaultTableColumnModel) tblBills.getColumnModel();
            TableColumn tblCol = model.getColumn(0);
            tblCol.setPreferredWidth(10);
        } catch (Exception ex) {
            try {
                ConnectionDB.CloseDB(ConnectionDB.ConnectionDatabase());
            } catch (Exception ex1) {
            }
            ex.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblId = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        lblCusName = new javax.swing.JLabel();
        txtCusname = new javax.swing.JTextField();
        lblDiscount = new javax.swing.JLabel();
        txtDiscount = new javax.swing.JTextField();
        lblVat = new javax.swing.JLabel();
        txtVat = new javax.swing.JTextField();
        lblPayment = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblBills = new javax.swing.JTable();
        lblTotal = new javax.swing.JLabel();
        lblTotalNumber = new javax.swing.JLabel();
        lblUserName = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        btnCreate = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        cboPayment = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("BillsDetail");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        lblId.setText("id");

        txtId.setEditable(false);

        lblCusName.setText("customer name");

        txtCusname.setEditable(false);

        lblDiscount.setText("discount");

        txtDiscount.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtDiscountKeyReleased(evt);
            }
        });

        lblVat.setText("VAT");

        txtVat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtVatKeyReleased(evt);
            }
        });

        lblPayment.setText("payment");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Items"));

        tblBills.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tblBills.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tblBillsMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tblBills);

        lblTotal.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblTotal.setText("jLabel1");

        lblTotalNumber.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(lblTotal)
                        .addGap(33, 33, 33)
                        .addComponent(lblTotalNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblTotal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblTotalNumber, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 11, Short.MAX_VALUE))
        );

        lblUserName.setText("user name");

        txtUsername.setEditable(false);

        btnCreate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-create.png"))); // NOI18N
        btnCreate.setText("jButton1");
        btnCreate.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnCreate.setPreferredSize(new java.awt.Dimension(100, 30));
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        btnUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-update.png"))); // NOI18N
        btnUpdate.setText("jButton1");
        btnUpdate.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnUpdate.setPreferredSize(new java.awt.Dimension(100, 30));
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-delete.png"))); // NOI18N
        btnCancel.setText("jButton1");
        btnCancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnCancel.setPreferredSize(new java.awt.Dimension(100, 30));
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        cboPayment.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblVat)
                            .addComponent(lblId)
                            .addComponent(lblDiscount))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(1, 1, 1)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtDiscount, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
                                    .addComponent(txtVat))))
                        .addGap(58, 58, 58)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblCusName)
                            .addComponent(lblPayment)
                            .addComponent(lblUserName))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtCusname, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                            .addComponent(txtUsername)
                            .addComponent(cboPayment, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(211, 211, 211))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblId)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCusName)
                    .addComponent(txtCusname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblUserName)
                        .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblDiscount)
                        .addComponent(txtDiscount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblPayment)
                        .addComponent(cboPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblVat)
                        .addComponent(txtVat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCreate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private boolean checkForm() {
        if (!CheckForm.isNumberic(txtDiscount.getText())) {
            JOptionPane.showMessageDialog(this, rb.getString("Discountmustbenumber") + ".", rb.getString("Warning"), JOptionPane.WARNING_MESSAGE);
            txtDiscount.selectAll();
            txtDiscount.requestFocus();
            return false;
        }
        if (!CheckForm.isNumberic(txtVat.getText())) {
            JOptionPane.showMessageDialog(this, rb.getString("Vatmustbenumber") + ".", rb.getString("Warning"), JOptionPane.WARNING_MESSAGE);
            txtVat.selectAll();
            txtVat.requestFocus();
            return false;
        }
        return true;
    }
    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
        try {
            // TODO add your handling code here:
            if (checkForm()) {
                try {
                    // TODO add your handling code here:
                    ItemHelper item = new ItemHelper();
                    paymenttemp = (PaymentHelper) cboPayment.getSelectedItem();
                    billsData = new BillsHepler();
                    billsData.setDiscount(txtDiscount.getText());
                    billsData.setVAT(txtVat.getText());
                    billsData.setId(txtId.getText());
                    billsData.setPID(paymenttemp.getId());
                    billsData.setTotal(lblTotalNumber.getText());
                    int query = BillsDAO.Update(ConnectionDB.ConnectionDatabase(), billsData);
                    if (query > 0) {
                        JOptionPane.showMessageDialog(this, rb.getString("Createsuccess") + ".", rb.getString("Message"), JOptionPane.INFORMATION_MESSAGE);

                        rs = BillsDAO.FindItemBill(ConnectionDB.ConnectionDatabase(), billsData);
                        while (rs.next()) {
                            ResultSet rs1 = ItemDAO.FindQuantity(ConnectionDB.ConnectionDatabase(), rs.getString("IId"));
                            if (rs1.next()) {
                                int quantity = Integer.parseInt(rs1.getString("QuantityAvailable")) - Integer.parseInt(rs.getString("Quantity"));
                                item.setId(rs.getString("IId"));
                                item.setQuantity(String.valueOf(quantity));
                                ItemDAO.UpdateQuantity(ConnectionDB.ConnectionDatabase(), item);
                            }
                        }
                        bills.reload();
                        this.dispose();
                    } else {
                        JOptionPane.showMessageDialog(this, rb.getString("CreateError") +".", rb.getString("Error"), JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception ex) {
                    Logger.getLogger(BillsDetail.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnCreateActionPerformed

    private void tblBillsMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblBillsMouseReleased
        // TODO add your handling code here:
        if (evt.getButton() == MouseEvent.BUTTON3) {
            try {
                Point p = new Point(evt.getXOnScreen(), evt.getYOnScreen());
                ((JMenuItem) popmenu1.getComponent(0)).setEnabled(false);
                popmenu1.setLocation(p);
                popmenu1.setVisible(true);
                //check
                int iRow = tblBills.rowAtPoint(new Point(evt.getX(), evt.getY()));
                Vector vtRootValue = new Vector();
                vtUpdate = new Vector();

                if (iRow >= 0) {
                    vtRootValue.addElement(tblBills.getModel().getValueAt(iRow, 0));
                    vtRootValue.addElement(tblBills.getModel().getValueAt(iRow, 1));
                    vtRootValue.addElement(tblBills.getModel().getValueAt(iRow, 2));
                    vtRootValue.addElement(tblBills.getModel().getValueAt(iRow, 3));
                    vtRootValue.addElement(tblBills.getModel().getValueAt(iRow, 4));

                    vtUpdate.addElement(tblBills.getValueAt(iRow, 0));
                    vtUpdate.addElement(tblBills.getValueAt(iRow, 1));
                    vtUpdate.addElement(tblBills.getValueAt(iRow, 2));
                    vtUpdate.addElement(tblBills.getValueAt(iRow, 3));
                    vtUpdate.addElement(tblBills.getValueAt(iRow, 4));

                    if (vtRootValue != vtUpdate) {
                        billsData.setId(txtId.getText());
                        billsData.setItemId(tblBills.getValueAt(iRow, 0).toString());
                        billsData.setQuantity(vtUpdate.get(3).toString());
                        ((JMenuItem) popmenu1.getComponent(0)).setEnabled(true);
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(Bills.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_tblBillsMouseReleased

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnUpdateActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        try {
            BillsDAO.DeleteBillsDetail(ConnectionDB.ConnectionDatabase(), txtId.getText());
            int query = BillsDAO.DeleteBills(ConnectionDB.ConnectionDatabase(), txtId.getText());
            if (query > 0) {
                JOptionPane.showMessageDialog(this, rb.getString("CanceledBills") + ".", rb.getString("Message"), JOptionPane.INFORMATION_MESSAGE);
                bills.reload();
                this.dispose();
            } else {
                JOptionPane.showMessageDialog(this, rb.getString("CanceledBillsError"), rb.getString("Error"), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnCancelActionPerformed
    double total;
    private void txtDiscountKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDiscountKeyReleased
         // TODO add your handling code here:
        
    }//GEN-LAST:event_txtDiscountKeyReleased

    private void txtVatKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtVatKeyReleased
        // TODO add your handling code here:
        total = Double.parseDouble(strTotal)  - Double.parseDouble(strTotal) * ((Double.parseDouble(txtDiscount.getText()) + Double.parseDouble(txtVat.getText())) / 100);
        lblTotalNumber.setText(String.valueOf(total));
    }//GEN-LAST:event_txtVatKeyReleased
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /*
//         * Set the Nimbus look and feel
//         */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /*
//         * If Nimbus (introduced in Java SE 6) is not available, stay with the
//         * default look and feel. For details see
//         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(BillsDetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(BillsDetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(BillsDetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(BillsDetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /*
//         * Create and display the dialog
//         */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                BillsDetail dialog = new BillsDetail(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnCreate;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JComboBox cboPayment;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCusName;
    private javax.swing.JLabel lblDiscount;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblPayment;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JLabel lblTotalNumber;
    private javax.swing.JLabel lblUserName;
    private javax.swing.JLabel lblVat;
    private javax.swing.JTable tblBills;
    private javax.swing.JTextField txtCusname;
    private javax.swing.JTextField txtDiscount;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtUsername;
    private javax.swing.JTextField txtVat;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the BillsId
     */
    public String getBillsId() {
        return BillsId;
    }

    /**
     * @param BillsId the BillsId to set
     */
    public void setBillsId(String BillsId) {
        this.BillsId = BillsId;
    }
}
